﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DOTNET_ASSIGNMENT.Models;
using DOTNET_ASSIGNMENT.Services;
using System.IO;
using System.Web.UI;

using System.Windows.Forms;

namespace DOTNET_ASSIGNMENT.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Contact()
        {
            return View();
        }

        public ActionResult DownloadPage(string aspxerrorpath)
        {
            var url = Request.Url.GetLeftPart(UriPartial.Authority) + aspxerrorpath;

            if (!String.IsNullOrEmpty(url))
            {
                FileServices fileServices = new FileServices();
                var file = fileServices.GetFileFromUrl(url);

                if (file != null)
                {
                    return View(file);
                }              
                else
                {
                    ModelState.AddModelError("", "File no longer exists!");
                }
            }
            return RedirectToAction("Index", "Home");
        }


        public ActionResult Download(string url)
        {
            FileServices fileServices = new FileServices();

            var databaseFile = fileServices.GetFileFromUrl(url);
            if (databaseFile == null) return RedirectToAction("Index", "Home");

            var name = databaseFile.DisplayName + "." + databaseFile.Extension;
            var path = Path.Combine(Server.MapPath("~/App_Data/Uploads/" + databaseFile.CustomerEmail.ToString()), name);

            if (System.IO.File.Exists(path))
            {
                var file = File(path, System.Net.Mime.MediaTypeNames.Application.Octet, name);
                return file;
            }         
            return RedirectToAction("Index", "Home");
        }
    }
}
